package cn.stylefeng.guns.modular.system.service;

import cn.stylefeng.guns.core.common.page.LayuiPageFactory;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.Arith;
import cn.stylefeng.guns.modular.system.entity.SysSchoolAgent;
import cn.stylefeng.guns.modular.system.entity.SysUserProfit;
import cn.stylefeng.guns.modular.system.entity.User;
import cn.stylefeng.guns.modular.system.mapper.SysUserProfitMapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

/**
 * <p>
 * 用户收益表 服务类
 * </p>
 *
 * @author zfy
 * @since 2020-08-13
 */
@Service
public class SysUserProfitService extends ServiceImpl<SysUserProfitMapper,SysUserProfit> {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private SysUserProfitLogService userProfitLogService;
    @Autowired
    private SysSchoolAgentService sysSchoolAgentService;

    public void add(String out_trade_no, Double total_fee) {
        String examText = (String) redisTemplate.opsForHash().get("exam", out_trade_no);
        if(ToolUtil.isNotEmpty(examText)){
            JSONObject json = JSON.parseObject(examText);
            User user = userService.getById(json.getString("createUser"));
            if(user.getRoleId().equals("1291579909321388034")){
                //学生
                user = userService.getById(user.getCreateUser());
            }

            //学校
            Double schoolProfit = Arith.mul(total_fee, Arith.div(user.getUserPercentage(), 100));
            userProfitAdd (schoolProfit,user.getUserId(),out_trade_no);

            //代理人
            Double agentProfit = Arith.sub(total_fee, schoolProfit);
            SysSchoolAgent agentBySchool = sysSchoolAgentService.getAgentBySchool(user.getUserId());
            if(ToolUtil.isNotEmpty(agentBySchool)){
                userProfitAdd (agentProfit,agentBySchool.getAgentUserId(),out_trade_no);
            }

        }
    }

    private void userProfitAdd (Double profit,Long userId,String outTradeNo){
        SysUserProfit userProfit = getUserProfit(userId);
        userProfit.setUserProfitAll(Arith.add(userProfit.getUserProfitAll(),profit));
        userProfit.setUserProfitRest(Arith.add(userProfit.getUserProfitRest(),profit));
        this.updateById(userProfit);
        userProfitLogService.add(profit,userId,outTradeNo);
    }

    public SysUserProfit getUserProfit (Long userId){
        SysUserProfit profit = this.getOne(new QueryWrapper<SysUserProfit>().eq("user_id", userId));
        if(profit == null){
            profit = new SysUserProfit();
            profit.setUserId(userId);
            profit.setCreaTime(LocalDateTime.now());
            this.save(profit);
        }
        return profit;
    }

    public IPage<Map<String,Object>> userProfitList(String schoolName, Integer state) {
          return this.baseMapper.userProfitList(LayuiPageFactory.defaultPage(),
                  schoolName, ShiroKit.isAdmin()?null:ShiroKit.getUserNotNull().getId(),state);
    }
}
